package malus.shaofeng.com.beiwomusic.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import malus.shaofeng.com.beiwomusic.R;
import malus.shaofeng.com.beiwomusic.adapter.StoryCommendAdapter;
import malus.shaofeng.com.beiwomusic.model.Comment;
import malus.shaofeng.com.beiwomusic.model.NewStory;
import malus.shaofeng.com.beiwomusic.utils.Constants;
import malus.shaofeng.com.beiwomusic.utils.SPHelper;
import malus.shaofeng.com.beiwomusic.view.SildingFinishLayout;
import malus.shaofeng.com.beiwomusic.view.Topbar;

/**
 * 故事的评论列表
 */
@ContentView(R.layout.activity_story_comment)
public class StoryCommentActivity extends Activity implements StoryCommendAdapter.OnReplyClickListener, View.OnClickListener {
    @ViewInject(R.id.storyCommendSildingFinishLayout)
    SildingFinishLayout finishLayout;
    @ViewInject(R.id.story_commend_pulltorefresh)
    PullToRefreshListView pullToRefresh;
    @ViewInject(R.id.layout_include_send)
    Button mSend;
    @ViewInject(R.id.layout_include_content)
    EditText mContent;
    @ViewInject(R.id.topbar)
    Topbar topbar;
    NewStory story;
    //回复的那个人,-1表示回复楼主
    int replyIndex=-1;

    int currentPage=1;
    int totalPage=1;
    int size=10;


    private ListView listView;
    private ArrayList<Comment> data;
    private StoryCommendAdapter adapter;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what){
                case 0:
                    //关闭刷新
                    if(pullToRefresh.isRefreshing()){
                        pullToRefresh.onRefreshComplete();
                    }
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        //设置topbar和右滑销毁
        initFinishClick();
        initView();
        mSend.setOnClickListener(this);
        setData();
    }

    /**
     * 一些初始化
     */
    private void initView(){
        mContent.setHint("添加评论");
        listView = pullToRefresh.getRefreshableView();
        data = new ArrayList<>();
        adapter = new StoryCommendAdapter(this, data);
        listView.setAdapter(adapter);
        Intent intent = getIntent();
       story= (NewStory)intent.getSerializableExtra(Constants.BundleKey.KEY_STORY);
        pullToRefresh.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if(currentPage<=1){
                    Toast.makeText(StoryCommentActivity.this,"亲，这已经是第一页啦",Toast.LENGTH_SHORT).show();
                }else{
                    currentPage--;
                    setData();
                }
                handler.sendEmptyMessageDelayed(0,500);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if(currentPage>=totalPage){
                    Toast.makeText(StoryCommentActivity.this,"亲，这已经是最后一页啦",Toast.LENGTH_SHORT).show();
                }else{
                    currentPage++;
                    setData();
                }
                handler.sendEmptyMessageDelayed(0,500);
            }
        });
    }

    /**
     * 标题栏和右滑销毁
     */
    private void initFinishClick(){
        finishLayout.setOnSildingFinishListener(new SildingFinishLayout.OnSildingFinishListener() {
            @Override
            public void onSildingFinish() {
                finish();
            }
        });
        topbar.setOnTopbarClickListener(new Topbar.onTopbarClickListener() {
            @Override
            public void onLeftButtonClick() {
                finish();
            }

            @Override
            public void onRightButtonClick() {

            }

            @Override
            public void onSearchButtonClick() {

            }
        });
    }
    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0,R.anim.trans_slider_out);
    }

    /**
     * 获取评论列表数据
     */
    private void setData(){
        final HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/comment/byStory.json";
        String token = SPHelper.getInstance().getToken();
        if(TextUtils.isEmpty(token)){
            Toast.makeText(this,"请先登录",Toast.LENGTH_SHORT).show();
            return;
        }
        if(story==null){
            Toast.makeText(this,"意外错误，找不到评论列表",Toast.LENGTH_SHORT).show();
            return ;
        }
        RequestParams params = new RequestParams();
        params.addBodyParameter("page",currentPage+"");
        params.addBodyParameter("pageSize",size+"");
        params.addBodyParameter("storyId",story.getStory_id()+"");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                String result = objectResponseInfo.result.toString();
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    JSONObject response = jsonObject.getJSONObject("response");
                    JSONObject paginator = response.optJSONObject("paginator");
                    if(paginator!=null){
                        totalPage=paginator.getInt("total_page");
                    }
                    JSONArray comments = response.getJSONArray("comments");
                    data.clear();
                    for (int i = 0; i < comments.length(); i++) {
                        JSONObject object = comments.getJSONObject(i);
                        Comment comment=new Comment();
                        comment.parseJSON(object);
                        data.add(comment);
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(StoryCommentActivity.this, "获取评论列表失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onReplyClick(int position) {
        this.replyIndex = position;
        mContent.setText("");
        mContent.setHint("回复："+data.get(replyIndex).getNickname());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.layout_include_send:
                Editable content = mContent.getText();
                if(content==null){
                    Toast.makeText(this,"回复不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
               if(replyIndex==-1){
                   replyLz();
               }else{
                   replyComment();
               }
                mContent.clearFocus();
                mContent.setText("");
                break;
        }
    }

    /**
     * 回复楼主
     */
    private void replyLz(){
        String token = SPHelper.getInstance().getToken();
        if(TextUtils.isEmpty(token)){
            Toast.makeText(this,"请先登录",Toast.LENGTH_SHORT).show();
            return;
        }
        String content = mContent.getText().toString();
        if(TextUtils.isEmpty(content)){
            Toast.makeText(this,"内容不能为空",Toast.LENGTH_SHORT).show();
            return;
        }

        HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/comment/create_3.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("token",token);
        params.addBodyParameter("storyId",story.getStory_id()+"");
        params.addBodyParameter("content", content);
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                setData();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(StoryCommentActivity.this, "回复失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 回复评论
     */
    private void replyComment(){
        String token = SPHelper.getInstance().getToken();
        if(TextUtils.isEmpty(token)){
            Toast.makeText(this,"请先登录",Toast.LENGTH_SHORT).show();
            return;
        }
        String content = mContent.getText().toString();
        if(TextUtils.isEmpty(content)){
            Toast.makeText(this,"内容不能为空",Toast.LENGTH_SHORT).show();
            return;
        }

        HttpUtils httpUtils=new HttpUtils();
        String url = "http://kxai.cn/qms/ws/comment/create_3.json";
        RequestParams params = new RequestParams();
        params.addBodyParameter("token",token);
        params.addBodyParameter("storyId",story.getStory_id()+"");
        params.addBodyParameter("content", content);
        params.addBodyParameter("refCommentId", data.get(replyIndex).getComment_id()+"");
        params.addBodyParameter("command", "608");
        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                setData();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(StoryCommentActivity.this, "回复失败", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
